package pl.edu.pw.MidEmu.Samples.MidasChat.Logic;

import midas.mw.cam.interfaces.Cam;
import midas.mw.cam.interfaces.ContextBasedAddress;
import midas.mw.interfaces.Mw;
import pl.edu.pw.MidEmu.Sensing.Sensors.ASensor;

/**
 * Helper class for sending messages from Middleware
 * @author Mateusz Starodab
 *
 */

public class Send
{
	private Cam cam;
	private Mw midas;

	/**
	 * Default constructor for Send class
	 * @param middlewareInterface
	 */
	public Send(Mw middlewareInterface)
	{
		this.midas = middlewareInterface;
		cam = (Cam) midas.getRunningComponent("CAM");
	}

	/**
	 * Method used for sending messages
	 * @param className Context class name
	 * @param message Message to be sent
	 * @param sensor Sensor which serves as data property
	 * @param value Sensor value
	 * @param operator for comparing sensor values
	 * @return
	 */
	public int sendMessage(String className, String message, ASensor sensor, String value, String operator)
	{
		try
		{
			ContextBasedAddress add = cam.makeCBA_InClass(className);

			if (sensor != null && !value.equals(""))
			{
				ContextBasedAddress tempAdd = cam.makeCBA_HasDataValue(sensor.getCkbName(), Float.parseFloat(value), operator);
				ContextBasedAddress finalAdd = cam.makeAddressIntersection(tempAdd, add);
				cam.sendMessage(finalAdd, message.getBytes(), 0);
			}
			else if (sensor != null && value.equals(""))
			{
				ContextBasedAddress tempAdd = cam.makeCBA_HasProperty(sensor.getCkbName());
				ContextBasedAddress finalAdd = cam.makeAddressIntersection(tempAdd, add);
				cam.sendMessage(finalAdd, message.getBytes(), 0);
			}
			else
			{
				cam.sendMessage(add, message.getBytes(), 0);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return 1;
		}
		return 0;
	}

	/**
	 * Terminates send component
	 */
	public void terminate()
	{
	}
}